// DOM元素
const loginForm = document.getElementById('loginForm');
const loginBtn = document.getElementById('loginBtn');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const notification = document.getElementById('notification');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否已经登录
    checkAuthStatus();
    
    // 设置事件监听器
    setupEventListeners();
    
    // 聚焦到用户名输入框
    usernameInput.focus();
});

// 设置事件监听器
function setupEventListeners() {
    // 表单提交
    loginForm.addEventListener('submit', handleLogin);
    
    // 回车键登录
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !loginBtn.disabled) {
            handleLogin(e);
        }
    });
    
    // 输入框变化时清除错误状态
    usernameInput.addEventListener('input', clearErrorState);
    passwordInput.addEventListener('input', clearErrorState);
}

// 检查登录状态
async function checkAuthStatus() {
    try {
        const response = await fetch('/api/auth/status');
        const data = await response.json();
        
        if (data.authenticated) {
            // 已登录，重定向到管理后台
            window.location.href = '/admin';
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
    }
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const username = usernameInput.value.trim();
    const password = passwordInput.value.trim();
    
    // 验证输入
    if (!username || !password) {
        showNotification('请输入用户名和密码', 'error');
        return;
    }
    
    // 设置加载状态
    setLoadingState(true);
    
    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showNotification('登录成功，正在跳转...', 'success');
            
            // 延迟跳转，让用户看到成功消息
            setTimeout(() => {
                window.location.href = '/admin';
            }, 1000);
        } else {
            showNotification(data.error || '登录失败', 'error');
            setErrorState();
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        showNotification('网络错误，请稍后重试', 'error');
        setErrorState();
    } finally {
        setLoadingState(false);
    }
}

// 设置加载状态
function setLoadingState(loading) {
    loginBtn.disabled = loading;
    if (loading) {
        loginBtn.classList.add('loading');
    } else {
        loginBtn.classList.remove('loading');
    }
    
    usernameInput.disabled = loading;
    passwordInput.disabled = loading;
}

// 设置错误状态
function setErrorState() {
    usernameInput.style.borderColor = '#ef4444';
    passwordInput.style.borderColor = '#ef4444';
    
    // 清空密码输入框
    passwordInput.value = '';
    
    // 聚焦到用户名输入框
    usernameInput.focus();
    usernameInput.select();
}

// 清除错误状态
function clearErrorState() {
    usernameInput.style.borderColor = '';
    passwordInput.style.borderColor = '';
}

// 显示通知
function showNotification(message, type = 'info') {
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 错误处理
window.addEventListener('error', function(e) {
    console.error('页面错误:', e.error);
    showNotification('页面发生错误，请刷新重试', 'error');
});

// 网络状态监听
window.addEventListener('online', function() {
    showNotification('网络连接已恢复', 'success');
});

window.addEventListener('offline', function() {
    showNotification('网络连接已断开', 'error');
});